package CronController

import (
	"arabApi/app/api/controllers"
	"arabApi/app/api/controllers/CFun"
	"arabApi/app/api/controllers/cronTask"
	"arabApi/app/api/models/CronModel"
	"arabApi/app/api/requests"
	"arabApi/app/api/requests/CRequest"
	"arabApi/app/api/requests/CronRequest"
	"arabApi/app/api/services/CronService"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/spf13/cast"
)

type Cron struct {
	controllers.BaseAPIController
}

func (s Cron) List(c *gin.Context) {
	//var cronreq = CronRequest.CronJob{}
	//
	//if err := c.ShouldBindQuery(&cronreq); err != nil{
	//	CFun.Ajax_return_fail(c, CFun.WithMsg("参数错误"+err.Error()))
	//	return
	//}

	cronList := CronModel.List()
	data := gin.H{}
	data["list"] = cronList
	data["count"] = 10
	CFun.Ajax_return_success(c, CFun.WithData(data))

}

func (s Cron) Add(c *gin.Context) {
	var cronreq = CronRequest.CronJob{}

	if err := c.ShouldBindQuery(&cronreq); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("参数错误"+err.Error()))
		return
	}

	if ok := requests.Validate(c, &cronreq, CronRequest.CheckCron); !ok {
		return
	}
	if cronreq.State == 1 {
		if id, err := cronTask.CronAdd(cronreq.Name, cronreq.Spec); err != nil {
			cronreq.State = 2
			//CFun.Ajax_return_fail(c, CFun.WithMsg("任务启动失败"))
		} else {
			cronreq.JobId = int64(id)
		}
	}

	_, ok := CronService.Add(cronreq)
	if ok != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("添加失败"))
		return
	}

	CFun.Ajax_return_success(c)
}

func (s Cron) Edit(c *gin.Context) {
	var cronreq = CronRequest.CronJob{}

	if err := c.ShouldBindBodyWith(&cronreq, binding.JSON); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("参数错误"+err.Error()))
		return
	}

	if ok := requests.Validate(c, &cronreq, CronRequest.CheckCron); !ok {
		return
	}

	cronD := CronService.FindOne(cronreq.ID)

	// 定时任务先停止
	if cronD.State != cronreq.State || cronD.Spec != cronreq.Spec {
		cronTask.CronDel(int(cronD.JobId))
	}

	if cronreq.State == 1 {
		if jobId, err := cronTask.CronAdd(cronreq.Name, cronreq.Spec); err != nil {
			CFun.Ajax_return_fail(c, CFun.WithMsg("任务启动失败"))
			return
		} else {
			cronreq.JobId = int64(jobId)
		}
	} else {
		cronreq.JobId = int64(0)
	}

	_, ok := CronService.Edit(cronreq)
	if ok != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("编辑失败"+ok.Error()))
		return
	}
	CFun.Ajax_return_success(c)
}

func (s Cron) CronMsg(c *gin.Context) {
	Id := CRequest.Oid{}
	if ok := c.ShouldBindQuery(&Id); ok != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("解析错误"))
	}

	if ok := requests.Validate(c, &Id, CRequest.CheckID); !ok {
		return
	}

	msg := CronService.FindOne(cast.ToInt64(Id.Id))
	CFun.Ajax_return_success(c, CFun.WithData(msg))
}

func (s Cron) Del(c *gin.Context) {

}
